<script lang="ts" setup>
import EZUIKit from "ezuikit-js";
import { onMounted, ref, computed, watch, onBeforeUnmount } from "vue";
import { getHomeChannelList } from "@/api/h3yun";
import VideoItem from "@/components/VideoItem.vue";
import { useUserStore } from "@/store/userStore";
const accessToken = 'at.81e76kp42jfjjpfxccxhii6b12gc8sh1-2323ajpbqc-19r9ke2-fmapebwsi'
const cameraList = ref([])
// 是否处于全屏模式
const isFullscreen = ref(false)
// 全屏显示的摄像头
const fullscreenCamera = ref(null)

const userStore = useUserStore()

// 使用遍历初始化多个播放器
const initData = async () => {
    const res = await getHomeChannelList(userStore.selectedAreaCode)
    if (res && res.code === '0' && res.data) {
      // 将接口返回的监控点数据转换为页面需要的格式
      let onlineCameras = res.data
      cameraList.value = onlineCameras.map((channel: any, index: number) => ({
        id: `video_dom_${index}`,
        name: channel.ChannelName,
        url: `ezopen://open.ys7.com/${channel.DeviceSerial}/${channel.ChannelNo}.live`,
        accessToken: accessToken,
        player: null,
        loading: false,
        error: false
      }))
    } else {
      console.error('获取监控点列表失败:', res)
    }
}

const playerSize = computed(() => {
  // 如果是全屏模式，返回更大的尺寸
  if (isFullscreen.value) {
    return {
      width: window.innerWidth,
      height: window.innerHeight
    };
  }
  
  // 获取容器尺寸
  const container = document.querySelector('.video-wrapper');
  let containerWidth = window.innerWidth;  // 默认使用窗口宽度
  let containerHeight = window.innerHeight; // 默认使用窗口高度
  
  if (container) {
    containerWidth = container.clientWidth;
    containerHeight = container.clientHeight;
  }
  
  // 计算两列布局时每个播放器的尺寸
  return {
    width: (containerWidth - 10) / 2, // 考虑间隔10px
    height: (containerHeight - 10) / 2 // 考虑间隔10px
  };
});

const initAllPlayer = () => {
    cameraList.value.forEach(camera => {
        initPlayer(camera)
    })
}

// 初始化播放器
const initPlayer = (camera) => {
  try {
    camera.loading = true;
    camera.error = false;
    
    // 如果已经存在播放器实例，先销毁它
    if (camera.player) {
      try {
        camera.player.stop();
        camera.player = null;
      } catch (e) {
        console.error("销毁播放器失败:", e);
      }
    }

    console.log(playerSize.value, '==playerSize==')
    
    // 获取播放器的尺寸
    const width = isFullscreen.value && fullscreenCamera.value === camera ? 
                  window.innerWidth : playerSize.value.width;
    const height = isFullscreen.value && fullscreenCamera.value === camera ? 
                  window.innerHeight : playerSize.value.height;
    
    // 创建新的播放器实例
    camera.player = new EZUIKit.EZUIKitPlayer({
      id: camera.id, // 视频容器ID
      accessToken: camera.accessToken,
      url: camera.url,
      template: "pcLive",
      audio: false, // 关闭音频
      plugin: ["talk"], // 加载插件，talk-对讲
      width: width,
      height: height,
      handleSuccess: () => {
        camera.loading = false;
      },
      handleError: (err: any) => {
        console.error("handleError", err);
        camera.loading = false;
        camera.error = true;
      },
      streamInfoCBType: 1,
    });
    
    return camera.player;
  } catch (error) {
    console.error("初始化播放器失败:", error);
    camera.loading = false;
    camera.error = true;
    return null;
  }
};

// 计算要显示的摄像头数量
const visibleCameras = computed(() => {
    // 固定显示4个摄像头
    return cameraList.value.slice(0, 4);
});

// 处理双击进入全屏
const handleDoubleClick = (item: any) => {
    item.player.fullScreen()
};

onMounted(async () => {
    await initData();
    initAllPlayer();
});
</script>

<template>
    <div class="video-wrapper">
        <div class="video-grid" v-for="(item, index) in visibleCameras">
            <VideoItem 
                :key="index" 
                :item="item"
                :index="index"
                @double-click="handleDoubleClick"
            />
        </div>
    </div>
</template>

<style lang="scss" scoped>
.video-wrapper {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  position: relative;
  display: flex;
  flex-wrap: wrap;
}

.video-grid {
  display: grid;
  gap: 10px;
//   width: 100%;
//   height: 100%;
  transition: all 0.3s;
  background-color: #1a1a1a;
}
</style>